<?php
namespace ScarecrowCache;

use ScarecrowCache\lib\ScarecrowFactory;

class ScarecrowCache{

	private static $cacheHandle=null;

	private function __construct(){}

	private static function creatCache()
	{
		if (self::$cacheHandle == null) {
			$factory = new ScarecrowFactory();
			self::$cacheHandle = $factory->execute('Cache');
		}
	}

	/**
	 * 插入一条数据
	 * @param $key
	 * @param $value
	 * @param int $flag
	 * @return mixed
	 */
	private static function insert($key, $value, $flag=S_DB_STORE)
	{
		$value = serialize($value);
		return self::$cacheHandle->insert($key, $value, $flag);
	}

	/**
	 * 查找一个key
	 * @param string $str
	 * @param null $default
	 * @return mixed
	 */
	private static function find(string $str, $default=null)
	{
		$data = self::$cacheHandle->fetch($str, $default);
		return unserialize($data);
	}

	/**
	 * 删除一个key
	 * @param string $key
	 * @return mixed
	 */
	private static function delete(string $key)
	{
		return self::$cacheHandle->delete($key);
	}

	/**
	 * 删除所有缓存
	 */
	private static function deleteAll()
	{
		self::$cacheHandle->deleteAllCache();
	}


	public static function __callStatic($name, $params=[])
	{
		self::creatCache();
		$obj = new \ReflectionClass(self::class);
		$methodObjList = $obj->getMethods(\ReflectionMethod::IS_STATIC);
		$allMethodList = [];
		foreach ($methodObjList as $item) {
			$allMethodList[] = $item->name;
		}
		unset($allMethodList['__callStatic']);
		if (in_array($name, $allMethodList)) {
			return call_user_func_array("self::{$name}", $params);
		} else {
			echo "你所调用的方法不存在!";
		}

	}
}